package cn.cvs.controller;

import cn.cvs.entity.SysUser;
import cn.cvs.service.sysUser.SysUserService;
import cn.cvs.utils.Constants;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {
    @Resource
    private SysUserService sysUserService;

    /**
     * 跳转到登录页面
     * @return
     */
    @RequestMapping(value="/toLogin")
    public String login(){
        return "login";
    }

    /**
     * 登录接口
     * @param account
     * @param password
     * @param request
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping("/login")
    public String doLogin(@RequestParam String account,@RequestParam String password,
                          HttpServletRequest request,HttpSession session) throws Exception{
        //调用service方法，进行用户匹配
        SysUser sysUser = sysUserService.login(account,password);
        if(null != sysUser){//登录成功
            session.setAttribute(Constants.USER_SESSION, sysUser);
            return "redirect:/sys/toMain";
        }else{
            request.setAttribute("error", "用户名或密码不正确");
            return "login";
        }
    }

    /**
     * 退出登录
     * @param session
     * @return
     */
    @RequestMapping("/logout")
    public String logout(HttpSession session){
        session.removeAttribute(Constants.USER_SESSION);
        return "login";
    }

    /**
     * 跳转到首页
     * @return
     */
    @RequestMapping("/sys/toMain")
    public String toMain(){
        return "frame";
    }

    @RequestMapping(value="/toSysError")
    public String sysError(){
        return "sysError";
    }
}

